package com.luo.filter;


import com.alibaba.fastjson2.JSON;
import com.luo.pojo.Results;
import com.luo.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@WebFilter("*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("登录验证开始");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("登录验证中");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        if (url.contains("login")) {
            log.info("登录验证放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            log.info("未登录");
            Results results = Results.error("NOT_LOGIN");
            String errorJson = JSON.toJSONString(results);
            response.getWriter().write(errorJson);
            return;
        }
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("非法令牌");
            Results results = Results.error("NOT_LOGIN");
            String errorJson = JSON.toJSONString(results);
            response.getWriter().write(errorJson);
            return;
        }
        log.info("登录验证成功");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("登录验证结束");
    }
}
